package com.study.crypto.basic.gb.util;

import com.study.crypto.basic.dto.gb.SealDataDto;
import com.study.crypto.basic.utils.SM4Utils;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.DERIA5String;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.DERUTF8String;

import java.io.IOException;
import java.security.GeneralSecurityException;

/**
 * @author Songjin
 * @since 2021-06-20 17:44
 */
public final class EncFileUtil {
    
    private EncFileUtil() {
    }
    
    /**
     * 根据备案印章信息生成公安加密文件
     *
     * @param dataSymKey 对称密钥
     * @param deviceCode 设备编号
     * @param sealData   印章信息
     * @return 加密文件，base64 编码
     */
    public static String capsulateEncFile(byte[] dataSymKey, String deviceCode, SealDataDto sealData) throws IOException, GeneralSecurityException {
        ASN1EncodableVector vector = new ASN1EncodableVector();
        vector.add(new DERIA5String(deviceCode));
        vector.add(new DERUTF8String(sealData.getYzmc()));
        vector.add(new DERIA5String(sealData.getYzbm()));
        vector.add(new DERIA5String(sealData.getYzzzdwbm()));
        vector.add(new DERIA5String(sealData.getYzlxdm()));
        vector.add(new DERUTF8String(sealData.getJbr_xm()));
        vector.add(new DERIA5String(sealData.getJbr_zjlx()));
        vector.add(new DERIA5String(sealData.getJbr_zjhm()));
        vector.add(new DERIA5String(sealData.getZzrq()));
        vector.add(new DERUTF8String(sealData.getYzsydw_dwmc()));
        vector.add(new DERUTF8String(sealData.getYzsydw_dwssmzwzmc()));
        vector.add(new DERUTF8String(sealData.getYzsydw_dwywmc()));
        vector.add(new DERUTF8String(sealData.getYzzzdw_dwmc()));
        vector.add(new DERUTF8String(sealData.getYzzzdw_dwssmzwzmc()));
        vector.add(new DERUTF8String(sealData.getYzzzdw_dwywmc()));
        vector.add(new DERUTF8String(sealData.getYzsydw_tyshxydm()));
        DERSequence sequence = new DERSequence(vector);
        byte[] plaintext = sequence.getEncoded();
        byte[] encoded = SM4Utils.encrypt_ecb_padding(dataSymKey, plaintext);
        return Base64.encodeBase64String(encoded);
    }
}
